<template>
  <section>
    <p>
      name:
      <input type="text" v-model="name" />
      {{ name }}
    </p>
    <p>
      age: <input type="text" v-model="age" />
      {{ age }}
    </p>
    <p>
      formData.name: <input type="text" v-model="formData.name" />
      {{ formData.name }}
    </p>
  </section>
</template>

<script lang="ts">
import { watchEffect, ref,watch, reactive} from "vue";

export default {
  setup() {
    const name = ref("Hydra");
    const age = ref("35");

    // watchEffect传递一个函数，函数内部使用到的响应式数据，只要发生变化，函数就会被触发执行
    // 内部得到的是变化后的新值
    watchEffect(() => {
        console.log("name = ",name.value);
        console.log("age = ",age.value);
    });

    watch(name,(newVal,oldVal) => {
        console.log("name.newVal = ",newVal);
        console.log("name.oldVal = ",oldVal);
    },{immediate: false,deep: false})

    // 侦听多个对象
    watch([name,age],(newVal,oldVal) => {
        // newVal和oldVal都是数组
        console.log("newVal = ",newVal);
        console.log("oldVal = ",oldVal);
    },{immediate: false,deep: false})

    let formData = reactive({
        name: "奉先"
    })
    
    // watch如果侦听的是对象中的数据，第一个参数需要通过一个函数来返回侦听的对象
    // 通常对象指的是reactive包装的对象，或者props传参
    watch(function() {return formData.name}
    ,(newVal,oldVal) => {
        // newVal和oldVal都是数组
        console.log("formData.newVal = ",newVal);
        console.log("formData.oldVal = ",oldVal);
    })



    return {
      name,
      age,
      formData
    };
  },
};
</script>

<style scoped>
</style>